package edu.mse.camel.client.posterboard.ui.editpart;

import org.eclipse.draw2d.ConnectionLayer;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.LayerConstants;
import org.eclipse.gef.Request;

import edu.mse.camel.client.posterboard.posterboard.PBDiagram;
import edu.mse.camel.client.posterboard.ui.adapters.WhiteboardAdapter;
import edu.mse.camel.client.posterboard.ui.editor.PosterBoardModelManager;
import edu.mse.camel.client.posterboard.ui.editpart.policy.PBDiagramComponentEditPolicy;
import edu.mse.camel.client.posterboard.ui.util.EditpartUtil;
import edu.mse.camel.client.whiteboard.gef.ui.editpart.WhiteboardDiagramEditPart;
import edu.mse.camel.client.whiteboard.gef.whiteboard.WhiteboardDiagram;

public class AdaptedWhiteboardDiagramEditpart 
	extends WhiteboardDiagramEditPart implements IPosterBoardDiagramEditpart {

	protected PBDiagram pbDiagram;
	
	protected EditpartListener listener;
	
	public AdaptedWhiteboardDiagramEditpart(PBDiagram pbDiagram, 
			PosterBoardModelManager pbModelManager) {
		super((WhiteboardDiagram) pbDiagram.getDelegate());
		WhiteboardDiagram delegate = (WhiteboardDiagram) pbDiagram.getDelegate();
		if (delegate.eResource() == null) {
			pbModelManager.addAdditionalWhiteboard(delegate);
		}
		this.pbDiagram = pbDiagram;
		setModel(pbDiagram.getDelegate());
		listener = new EditpartListener(this);
	}

	@Override
	protected IFigure createFigure() {
		return EditpartUtil.createFigure(getModel(), 
				(ConnectionLayer) getLayer(LayerConstants.CONNECTION_LAYER));
	}

	@Override
	protected void createEditPolicies() {
		super.createEditPolicies();
		installEditPolicy(EditPolicy.COMPONENT_ROLE, new PBDiagramComponentEditPolicy());
	}

	public PBDiagram getPbDiagram() {
		return pbDiagram;
	}

	@Override
	public void activate() {
		if (this.isActive()) {
			return;
		}
		super.activate();
		pbDiagram.eAdapters().add(listener);
	}
	
	@Override
	public void deactivate() {
		if (!this.isActive()) {
			return;
		}
		super.deactivate();
		pbDiagram.eAdapters().remove(listener);
	}
	
	public WhiteboardDiagram getCastedModel() {
		return (WhiteboardDiagram) getModel();
	}
	
	@Override
	public void refreshVisuals() {
		super.refreshVisuals();
		EditpartUtil.refreshVisuals(getCastedModel(), this);
	}

	@Override
	protected void fireSelectionChanged() {
		super.fireSelectionChanged();
		EditpartUtil.diagramSelectionChanged(this);
	}
	
	@Override
	public DragTracker getDragTracker(Request req){
		return EditpartUtil.getDragTracker(req, this);
	}
	
	public String getType() {
		return WhiteboardAdapter.WHITEBOARD_DIAGRAM;
	}

}
